package com.example.lenovo.mywechat.temp.chat_page;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.lenovo.mywechat.R;
import com.example.lenovo.mywechat.homepage.HomepageActivity;
import com.example.lenovo.mywechat.login.Login;
import com.google.protobuf.ByteString;
import com.snow.proto.my_wechat.GroupId;
import com.snow.proto.my_wechat.GroupMessage;
import com.snow.proto.my_wechat.GroupMessages;
import com.snow.proto.my_wechat.MyWeChatServiceGrpc;
import com.snow.proto.my_wechat.SendState;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Lenovo on 2018/9/18.
 */
public class ChatPageActivity extends Activity {
    GroupMessage groupMessage;

    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;

    private boolean mRun;
    private String mMessageWaitingForSend = null;
    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x1001) {
//                adapter.notifyItemInserted(msgList.size() - 1);
//                msgRecyclerView.scrollToPosition(msgList.size() - 1);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.chat_page);

        initMsgs();//初始化消息数据

        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        msgRecyclerView = findViewById(R.id.msg_recycler_view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();
                if (!"".equals(content)) {
                    mMessageWaitingForSend = content;

                    int group_id = getIntent().getIntExtra("group_id", -1);
                    long creation_time = System.currentTimeMillis();
                    int user_id = HomepageActivity.userInfo.getId();
                    String content_type = "String";
                    ByteString contentByteString = ByteString.copyFrom(content.getBytes());

                    MyWeChatServiceGrpc.MyWeChatServiceBlockingStub blockingStub = MyWeChatServiceGrpc.newBlockingStub(HomepageActivity.managedChannel);
                    SendState sendState = blockingStub.sendGroupMessageByGroupId(
                            GroupMessage.newBuilder()
                                    .setGroupId(group_id)
                                    .setCreationTime(creation_time)
                                    .setUserId(user_id)
                                    .setContentType(content_type)
                                    .setContent(contentByteString).build()
                    );
                    if (!sendState.getSendState()){
                        contentByteString = ByteString.copyFrom((content + "(发送失败)").getBytes());
                    }

                    Msg msg = new Msg(group_id, creation_time, user_id, HomepageActivity.userInfo.getAvatar(), content_type, contentByteString);
                    msgList.add(msg);//增加消息到集合中。
//                    Toast.makeText(ChatPageActivity.this, msgList.size()+"a", Toast.LENGTH_SHORT).show();
                    adapter.notifyItemInserted(msgList.size() - 1);//当有新消息时，刷新RecyclerView中的显示。本质就是此位置和后续的消息直接往下移动，刷新此位置。
//                    adapter.notifyItemRangeChanged(msgList.size() - 1, 1);//只刷新最后一个信息。与上面的一行代码有类似作用。
//                    adapter.notifyItemRangeChanged(0, msgList.size());//刷新所有信息组件，也可以指定位置刷新
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);//将RecyclerView定位到最后一行。即滑动到能显示最后一条消息的位置。
                    inputText.setText("");//清空输入框中的内容
                }
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                mRun = true;

                MyWeChatServiceGrpc.MyWeChatServiceBlockingStub blockingStub = MyWeChatServiceGrpc.newBlockingStub(HomepageActivity.managedChannel);
                Iterator<GroupMessage> iter = blockingStub.getGroupMessage(
                    GroupId.newBuilder().setGroupId(getIntent().getIntExtra("group_id", -1)).build()
                );

                while (iter.hasNext()){
                    groupMessage = iter.next();

                    if (groupMessage.getUserId() != HomepageActivity.userInfo.getId()){
                        msgList.add(new Msg(
                                groupMessage.getGroupId(),
                                groupMessage.getCreationTime(),
                                groupMessage.getUserId(),
                                ByteString.copyFrom(getIntent().getByteArrayExtra("avatar")),
                                groupMessage.getContentType(),
                                groupMessage.getContent()
                        ));
                        ChatPageActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyItemInserted(msgList.size() - 1);
                                msgRecyclerView.scrollToPosition(msgList.size() - 1);
                            }
                        });
                    }
                }

//                try {
//                    Socket connection = new Socket("192.168.49.60", 8080);
//                    OutputStream out = connection.getOutputStream();
//                    InputStream in = connection.getInputStream();
//                    byte[] readBuffer = new byte[1024];
//                    while(mRun) {
//                        if (mMessageWaitingForSend != null) {
//                            out.write(mMessageWaitingForSend.getBytes());
//                            out.flush();
//                            int length = in.read(readBuffer);
//                            String reply = new String(readBuffer, 0, length);
//                            Log.d("ChatActivity++++++++++", reply);
//                            msgList.add(new Msg(reply, Msg.TYPE_RECEIVED));
//                            mMessageWaitingForSend = null;
//                            mHandler.sendEmptyMessage(0x1001);
//                        }
//                        Thread.sleep(1000);
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        }).start();
    }
    private void initMsgs() {
        MyWeChatServiceGrpc.MyWeChatServiceBlockingStub blockingStub = MyWeChatServiceGrpc.newBlockingStub(HomepageActivity.managedChannel);
        GroupMessages groupMessages = blockingStub.getGroupMessagesByGroupId(
                GroupId.newBuilder().setGroupId(getIntent().getIntExtra("group_id", -1)).build()
        );
        GroupMessage groupMessage;
        Msg msg;
        for (int i = 0; i < groupMessages.getGroupMessageCount(); i++){
            groupMessage = groupMessages.getGroupMessage(i);

            if (groupMessage.getUserId() == HomepageActivity.userInfo.getId()){
                msg = new Msg(
                        groupMessage.getGroupId(),
                        groupMessage.getCreationTime(),
                        groupMessage.getUserId(),
                        HomepageActivity.userInfo.getAvatar(),
                        groupMessage.getContentType(),
                        groupMessage.getContent()
                );
            }else{
                msg = new Msg(
                        groupMessage.getGroupId(),
                        groupMessage.getCreationTime(),
                        groupMessage.getUserId(),
                        ByteString.copyFrom(getIntent().getByteArrayExtra("avatar")),
                        groupMessage.getContentType(),
                        groupMessage.getContent()
                );
            }

            msgList.add(msg);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRun = false;
    }
}
